import { Model, DataTypes, Optional } from 'sequelize';
import { sequelize } from '../../config/database';
import User from './User';

// 用户快照接口
interface UserSnapshotAttributes {
  id: string;
  userId?: string | null;
  userName?: string | null;
  userAvatar?: string | null;
  payGrade?: number | null;
  fansLevel?: number | null;
  fansClubName?: string | null;
  // 管理员权限字段
  isAdmin?: boolean | null;
  createdAt?: Date;
}

// 创建时可选的属性
interface UserSnapshotCreationAttributes extends Optional<UserSnapshotAttributes, 'id' | 'createdAt'> {}

// 用户快照模型类
class UserSnapshot extends Model<UserSnapshotAttributes, UserSnapshotCreationAttributes> implements UserSnapshotAttributes {
  declare id: string;
  declare userId: string | null;
  declare userName: string | null;
  declare userAvatar: string | null;
  declare payGrade: number | null;
  declare fansLevel: number | null;
  declare fansClubName: string | null;
  // 管理员权限字段
  declare isAdmin: boolean | null;
  
  // 时间戳
  declare readonly createdAt: Date;
}

// 初始化模型
UserSnapshot.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      allowNull: false
    },
    userId: {
      type: DataTypes.STRING,
      allowNull: true
    },
    userName: {
      type: DataTypes.STRING,
      allowNull: true
    },
    userAvatar: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    payGrade: {
      type: DataTypes.INTEGER,
      allowNull: true,
      defaultValue: 0
    },
    fansLevel: {
      type: DataTypes.INTEGER,
      allowNull: true,
      defaultValue: 0
    },
    fansClubName: {
      type: DataTypes.STRING,
      allowNull: true
    },
    // 管理员权限字段
    isAdmin: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: false
    }
  },
  {
    sequelize,
    tableName: 'user_snapshots',
    modelName: 'UserSnapshot',
    timestamps: true,
    updatedAt: false, // 快照不需要更新时间
    indexes: [
      {
        fields: ['userId', 'createdAt']
      }
    ]
  }
);

// 设置关联关系（禁用外键约束）
UserSnapshot.belongsTo(User, { foreignKey: 'userId', as: 'user', constraints: false });

User.hasMany(UserSnapshot, { foreignKey: 'userId', as: 'snapshots', constraints: false });

export default UserSnapshot;